// pages/index/currentdesire/currentdesire.js

import {
    GetHewillList, // 列表
    GetHewilldtlZyzmove, // 专业上下移动
    GetHewilldtlZydel, // 专业删除
    GetHewillZyzmove,// 专业组上下移动
    GetHewillZyzdel,// 专业组删除
    GetHewillUpdate, // 调剂
    GetStudentgradesZyzadd, // 弹窗专业数据源
    GetHewillAdd, // 填报
    GetStudentgrades, // 我的成绩查询
    GetZyzdelall, // 删除全部专业组
    GetSendEmailPDF, // 发送PDF
} from '../../../api/index'
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // dataSourceArray: [{
        //         dictType: "ols_question_from",
        //         dictValue: "A",
        //         dictLabel: "本科批"
        //     },
        //     {
        //         dictType: "ols_question_from",
        //         dictValue: "B",
        //         dictLabel: "专科批"
        //     }
        // ],
        listArray: [],
        // chooseIndex:0,
        changTitle: '本科批',
        addIndex:0, // 添加的下标
        fill_show: false,
        fillProfessionList:[], // 可填报专业数据源
        title:'',
        gradesArray:[],
        emaill_show:false,
        emaillString:'',
        openVip:app.globalData.openVip,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log(options)
        // if (options.type == '本科批') {
        //     this.setData({
        //         chooseIndex:0,
        //         changTitle: '本科批',
        //     })
        // } else {
        //     this.setData({
        //         chooseIndex:1,
        //         changTitle: '专科批',
        //     })
        // }

        let openid = wx.getStorageSync('openId') || '';
        this._GetStudentgrades('?openId=' + openid, false)
        
    },
    // 重要提示
    importHintAction() {
        if (this.data.openVip != 1) {
            wx.navigateTo({
                url: '/pages/mine/openvip/openvip',
              })
            return
        }
        this.setData({
            emaill_show:true
        })
    },

    // 输入框输入事件
    inputEvent(event) {
        console.log(event)
        let id = event.currentTarget.id;
        let value = event.detail.value;
        this.setData({
            emaillString:value
        })
    },


       // 发送PDF到邮箱
       makeShowAction() {
        
        this.setData({
            emaill_show:false
        })
        var reg = new RegExp('^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$');       
        var emailVar = reg.test(this.data.emaillString);     // 得到的值为布尔型
        if (emailVar == true) {
            // Toast('邮箱正确');
        this._GetSendEmailPDF({toEmail:this.data.emaillString,dataType:'2'},true);
        } else {
            Toast('请填写正确邮箱');
            return
        }
    },

    // 发送PDF到邮箱
_GetSendEmailPDF(data, isLoading) {
    GetSendEmailPDF(data, isLoading).then(res => {
        console.log(res)
        let code = res.code;
        if (code == 200) {
            this.setData({
                emaillString:''
            })
            Toast({
                type: 'success',
                message: '发送成功',
              });
        } else {
            Toast(res.msg)
        }
    })
},

    // 去填报
  submitAction() {
      if (this.data.gradesArray.length == 0) { // 未设置分数
        Dialog.confirm({
            title: '未设置分数',
            message: '请先设置分数',
        })
        .then(() => {
            // on confirm
            wx.navigateTo({
              url: '/pages/mine/editgrade/editgrade',
            })
        })
        .catch(() => {
            // on cancel
        });
          return
      }
    wx.navigateTo({
      url: '/pages/index/intelligentfilling/intelligentfilling',
    })
},

// 清空
clearAction() {
    if (this.data.listArray.length == 0) {
        return
    }
    let that = this;
    let openid = wx.getStorageSync('openId') || '';
    Dialog.confirm({
        title: '清空全部专业组',
        message: '是否清空全部专业组',
    })
    .then(() => {
        // on confirm
        
        that._GetZyzdelall({
            openId: openid,
            willType:that.data.changTitle
        }, true)
    })
    .catch(() => {
        // on cancel
    });
},

    // tab切换
    // onChange(event) {
    //     console.log(event)
    //     this.setData({
    //         changTitle: event.detail.title
    //     })
    //     let openid = wx.getStorageSync('openId') || '';
    //     this._GetHewillList('?openId=' + openid + "&willType=" + this.data.changTitle, true)
    // },

    // 删除专业点击事件
    itemRemoveAction(event) {
        let item = event.currentTarget.dataset.item
        let that = this;
        let title = item.zydhmc;
        Dialog.confirm({
            title: title,
            message: '是否删除该专业',
        })
        .then(() => {
            // on confirm
            that._GetHewilldtlZydel({
                dtlId: item.dtlId
            }, true)
        })
        .catch(() => {
            // on cancel
        });
        
    },

    // 上移专业点击事件
    itemUpAction(event) {
        let item = event.currentTarget.dataset.item
        let itemindex =  event.currentTarget.dataset.itemindex
        let index = event.currentTarget.dataset.index
        let listArray = this.data.listArray.slice()
            let arr = listArray[index].dtlList.slice()
            arr.splice(itemindex - 1, 0, arr.splice(itemindex, 1)[0]);
            this.setData({
                ['listArray[' + index + '].dtlList']: arr,
            })
        this._GetHewilldtlZyzmove({
            moveType: 'up',
            dtlId: item.dtlId
        }, true);
    },

    // 下移专业点击事件
    itemDownAction(event) {
        let item = event.currentTarget.dataset.item
        let itemindex =  event.currentTarget.dataset.itemindex
        let index = event.currentTarget.dataset.index
        let listArray = this.data.listArray.slice()
            let arr = listArray[index].dtlList.slice()
            let resultArray = this.moveElementDown(arr, itemindex);
            this.setData({
                ['listArray[' + index + '].dtlList']: resultArray,
            })
        // if (changeType == 'up') {
            
        // } else {
        //     let arr = this.data.listArray.slice()
        //     let nowArray = this.moveDownInArray(arr, changeIndex);
        //     this.setData({
        //         listArray:nowArray
        //     })
        // }
        this._GetHewilldtlZyzmove({
            moveType: 'down',
            dtlId: item.dtlId
        }, true);
    },

     moveElementDown(arr, index) {
        if (index >= arr.length - 1) return arr; // 如果是最后一个元素，不进行操作
        // 将指定索引的元素下移，同时将下一个元素上移到原来的位置
        [arr[index], arr[index + 1]] = [arr[index + 1], arr[index]];
        return arr;
      },

    // 删除专业组点击事件
    listRemoveAction(event) {
        console.log(event)
        let item = event.currentTarget.dataset.item
        let index = event.currentTarget.dataset.index
        let that = this;
        let title = item.yxmc;
        Dialog.confirm({
            title: title,
            message: '是否删除该专业组',
        })
        .then(() => {
            // on confirm
            that._GetHewillZyzdel(
                {id: item.id}, true, index)
        })
        .catch(() => {
            // on cancel
        });
        
    },

    // 上移专业组点击事件
    listUpAction(event) {
        let item = event.currentTarget.dataset.item
        let index = event.currentTarget.dataset.index
        if (index == 0) {
            console.log('第一个不能向上移动')
            return
        }
        this._GetHewillZyzmove({
            moveType: 'up',
            id: item.id
        }, true, index,'up')
    },

    // 下移专业组点击事件
    listDownAction(event) {
        let item = event.currentTarget.dataset.item
        let index = event.currentTarget.dataset.index
        if (index == this.data.listArray.length - 1) {
            console.log('最后一个个不能向下移动')
            return
        }
        this._GetHewillZyzmove({
            moveType: 'down',
            id: item.id
        }, true, index,'down')
    },

    // 调剂
    tiaojiAction(event) {
        let item = event.currentTarget.dataset.item
        let index = event.currentTarget.dataset.index
        console.log(item)
        let isTiaoji = item.isTiaoji == 0 ? 1 : 0
        this.setData({
            ['listArray[' + index + '].isTiaoji']: isTiaoji,
        })
        this._GetHewillUpdate({id:item.id,isTiaoji:isTiaoji}, true);
    },

    // 点击添加
    addListAction(event) {
        let item = event.currentTarget.dataset.item
        let index = event.currentTarget.dataset.index
        let openid = wx.getStorageSync('openId') || '';
        this.setData({
            addIndex:index,
            chooseFillModel:item
        })
        this._GetStudentgradesZyzadd({openId:openid,kldm:item.kldm,pcdm:item.pcdm,yxdh:item.yxdh,zyzdh:item.zyzdh})
    },
     // 关闭专业选择
     onCloseFillAction() {
        this.setData({
            fill_show: false,
            emaill_show:false,
        })
    },

    // 填报点击事件
    fillAction(event) {
        console.log(event)
        console.log(this.data.chooseFillModel)
        let item = event.currentTarget.dataset.item
        let index = event.currentTarget.dataset.index
      
        let openid = wx.getStorageSync('openId') || '';
        if (item.isTianBao == 1) {
            this.setData({
                ['fillProfessionList[' + index + '].isTianBao']: item.isTianBao == 1 ? 0 : 1,
            })
            this._GetHewilldtlZydel({
                dtlId: item.dtlId
            }, true)
        } else {
            this._GetHewillAdd({openId:openid, kldm:this.data.chooseFillModel.kldm,pcdm:this.data.chooseFillModel.pcdm,yxdh:this.data.chooseFillModel.yxdh,zyzdh:this.data.chooseFillModel.zyzdh,zyzType:this.data.chooseFillModel.zyzType,zsjhId:item.zsjhId, zyType:item.zyType}, true, index, item);
        }
    },

    // 列表
    _GetHewillList(data, isLoading) {
        GetHewillList(data, isLoading).then(res => {
            console.log(res)
            let code = res.code;
            // Toast('成功')
            if (code == 200) {
                this.setData({
                    listArray: res.rows
                })
            } else {
                Toast(res.msg)
            }
        })
    },

    // 专业上下移动
    _GetHewilldtlZyzmove(data, isLoading) {
        console.log(data)
        GetHewilldtlZyzmove(data, isLoading).then(res => {
            console.log(res)
            let code = res.code;
            // Toast('成功')
            if (code == 200) {

            } else {
                Toast(res.msg)
            }
        })
    },


    // 专业删除
    _GetHewilldtlZydel(data, isLoading) {
        GetHewilldtlZydel(data, isLoading).then(res => {
            console.log(res)
            let code = res.code;
            // Toast('成功')
            if (code == 200) {
                let openid = wx.getStorageSync('openId') || '';
                this._GetHewillList('?openId=' + openid + "&willType=" + this.data.changTitle, false)
            } else {
                Toast(res.msg)
            }
        })
    },

    // 专业组上下移动
    _GetHewillZyzmove(data, isLoading, changeIndex, changeType) {
        console.log(data)
        GetHewillZyzmove(data, isLoading).then(res => {
            console.log(res)
            let code = res.code;
            // Toast('成功')
            if (code == 200) {
                if (changeType == 'up') {
                    let arr = this.data.listArray.slice()
                    arr.splice(changeIndex - 1, 0, arr.splice(changeIndex, 1)[0]);
                    this.setData({
                        listArray:arr
                    })
                } else {
                    let arr = this.data.listArray.slice()
                    let nowArray = this.moveDownInArray(arr, changeIndex);
                    this.setData({
                        listArray:nowArray
                    })
                }

            } else {
                Toast(res.msg)
            }
        })
    },

   moveDownInArray(arr, index) {
        if (index >= arr.length - 1) return arr; // 如果是最后一个元素，不需要移动
        // 使用splice方法交换位置
        [arr[index], arr[index + 1]] = [arr[index + 1], arr[index]];
        return arr;
      },
       

    // 专业组删除
    _GetHewillZyzdel(data, isLoading, removeIndex) {
        GetHewillZyzdel(data, isLoading).then(res => {
            console.log(res)
            let code = res.code;
            // Toast('成功')
            if (code == 200) {
                let arr = this.data.listArray.slice()
                arr.splice(removeIndex, 1);
                this.setData({
                    listArray:arr
                })
            } else {
                Toast(res.msg)
            }
        })
    },


    // 调剂
    _GetHewillUpdate(data, isLoading) {
        GetHewillUpdate(data, isLoading).then(res => {
            console.log(res)
            let code = res.code;
            // Toast('成功')
            if (code == 200) {

            } else {
                Toast(res.msg)
            }
        })
    },


//  弹框专业数据源
_GetStudentgradesZyzadd(data, isLoading) {
    console.log(data)
    GetStudentgradesZyzadd(data, isLoading).then(res => {
        console.log('弹框专业数据源')
        console.log(res)
        let code = res.code;
        if (code == 200) {
            let array = res.data.zyList
           
            if (array.length != 0) {
                this.setData({
                    chooseFillModel:res.data,
                    fill_show:true,
                    fillProfessionList:array
                })
            }
        } else {
            Toast(res.msg)
        }
    })
},

//  填报
_GetHewillAdd(data, isLoading, chooseIndex, item) {
    console.log(data)
    GetHewillAdd(data, isLoading).then(res => {
        console.log('填报')
        console.log(res)
        let code = res.code;
        if (code == 200) {
            let rtnType = res.data.rtnType;
            if (rtnType != 1) {
                Toast(res.data.rtnMsg)
                return
            }
    
            this.setData({
                ['fillProfessionList[' + chooseIndex + '].isTianBao']: 1,
                ['fillProfessionList[' + chooseIndex + '].dtlId']: res.data,
            })
            console.log(this.data.fillProfessionList)
            let openid = wx.getStorageSync('openId') || '';
            this._GetHewillList('?openId=' + openid + "&willType=" + this.data.changTitle, false)
        } else {
            Toast(res.msg)
        }
    })
},


//  删除全部专业组
_GetZyzdelall(data, isLoading) {
    console.log(data)
    GetZyzdelall(data, isLoading).then(res => {
        console.log('删除全部专业组')
        console.log(res)
        let code = res.code;
        if (code == 200) {
            this.setData({
                listArray:[]
            })
        } else {
            Toast(res.msg)
        }
    })
},

// 我的成绩查询
_GetStudentgrades(data, isLoading) {
    GetStudentgrades(data, isLoading).then(res => {
        console.log(res)
        let code = res.code;
        // Toast('成功')
        if (code == 200) {
            let array = res.rows;
            this.setData({
                gradesArray:array
            })
            let title = '黑龙江 · '
            let mutableArray = [];
            if (array.length != 0) {
                let model = array[0]
                if (model.isWuli == 1) {
                    title += "物 | "
                    // mutableArray.push('物理')
                } else {
                    title += "历 | "
                    // mutableArray.push('历史')
                }
                if (model.isHuaxue == 1) {
                    title += "化"
                    // mutableArray.push('化学')
                }
                if (model.isShengwu == 1) {
                    title += "生"
                    // mutableArray.push('生物')
                }
                if (model.isZhengzhi == 1) {
                    title += "政"
                    // mutableArray.push('政治')
                }
                if (model.isDili == 1) {
                    title += "地"
                    // mutableArray.push('地理')
                }
                let str = mutableArray.join(' / '); // 使用逗号分隔
                let content = title + str + '  ' + model.myScore + '分 ' + model.myWeici + '名'
                console.log(content)
                this.setData({
                    title:content,
                    changTitle:model.reserve1,
                })
                let openid = wx.getStorageSync('openId') || '';
                this._GetHewillList('?openId=' + openid + "&willType=" + this.data.changTitle, true)
            }
        } else {
            // Toast(res.msg)
        }
    })
},



    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        // 可以在这里编写你需要的逻辑
        console.log('返回按钮被点击');
        //保存成功返回上一页 获取上一个页面的实例对象
        var pages = getCurrentPages()
        // 拿到上一个页面的索引
        var previousPage = pages[pages.length - 2];
            // 调用上一页的 nav_page方法
        previousPage.navpage()
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    onShareTimeline: function (){

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})